/**
 * TrayIconListener.java 2008-05-19
 * 
 * Linker is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

package linker.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import linker.Settings;
import linker.list.ViewList;

/**
 * The listener of tryicon.
 * 
 * @version 2008-05-20
 * @author Jianfeng tujf.cn@gmail.com
 * @author Tan tan1986@gmail.com
 * 
 */

public class TrayIconListener extends MouseAdapter {

	/**
	 * MainWindow refer.
	 */
	private MainWindow mainWindow;

	/**
	 * TrayIconPopup refer.
	 */
	private TrayIconPopup trayPopup;

	/**
	 * Self.
	 */
	private static TrayIconListener listener;

	/**
	 * The flag of open first or not.If true when trayicon is clicked the first
	 * message in the message list will be opened.
	 */
	private boolean openFirst = true;

	/**
	 * Get the single TrayIconListener.
	 * 
	 * @param mainWindow
	 *            The mainWindow
	 * @param trayPopup
	 *            The popupMenu of trayicon
	 * @return The singal TrayIconListener.
	 */
	public static TrayIconListener getTrayIconListener(
			final MainWindow mainWindow, final TrayIconPopup trayPopup) {
		if (listener != null) {
			return listener;
		}

		listener = new TrayIconListener();
		listener.mainWindow = mainWindow;
		listener.trayPopup = trayPopup;
 
		String openFirstStr = Settings.getSettings().getValue("openfirst");
		if (openFirstStr != null) {
			listener.openFirst = Boolean.valueOf(openFirstStr);
		}
		return listener;
	}

	/**
	 * The trayicon mouse click action.
	 * 
	 * @param e
	 *            MouseEvent
	 */
	public final void mouseClicked(final MouseEvent e) {
		if (e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1) {

			if (!openFirst || !ViewList.getMessageList().openFirst()) {
				listener.mainWindow
						.setVisible(!listener.mainWindow.isVisible());

				trayPopup.setShowCheckBox(listener.mainWindow.isVisible());
			}
		}
	}

	/**
	 * Set open first flag.
	 * 
	 * @param value
	 *            The value replace the value before.
	 */
	public static void setOpenFirst(final Boolean value) {
		listener.openFirst = value;
	}

}
